import React, { useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import AudioController from '../../components/basic/AudioController';
import ProgressBar from '@compa/ProgressBar';
import { closeSongPage, toggleLyrics } from '../../store/actions/music.action';
import { displayLyrics, formatSongTimeText, generateArtists } from '../../utils/common';
import './index.css';

const mapStateToProps = state => {
    return {
        music: state.music
    }
}
const mapDispatchToProps = dispatch => {
    return {
        closeSongPage: (...args) => dispatch(closeSongPage(...args)),
        toggleLyrics: (...args) => dispatch(toggleLyrics(...args))
    }
}

const SongPage = ({ music, closeSongPage, toggleLyrics }) => {
    const lyricWrapperRef = useRef();
    useEffect(() => {
        console.log("SongPage: ", music.curSong);
        if (lyricWrapperRef.current && lyricWrapperRef.current.childElementCount > 0) {
            let container = lyricWrapperRef.current,
                initialTop = container.getBoundingClientRect().height / 2,
                lineHeight = container.lastChild.firstChild.offsetHeight,
                content = container.lastChild,
                currentIndex = 0;
            content.ontouchstart = function (e) {
                e.stopPropagation();
                console.log("touchstart", this.offsetTop, (initialTop - this.offsetTop) / lineHeight)
                function lyricContentMoveHandler() {
                    let index = Math.floor((initialTop - this.getBoundingClientRect().top) / lineHeight);
                    if (index !== currentIndex) {
                        console.log("move", this.getBoundingClientRect().top, index);
                        music.curSong.audio.currentTime = formatSongTimeText(music.curSong.lrc.timeArr[index]);
                        currentIndex = index;
                    }
                }
                content.ontouchmove = lyricContentMoveHandler.bind(this);
                content.ontouchend = function () {
                    let index = Math.floor((initialTop - this.getBoundingClientRect().top) / lineHeight);
                    console.log("touchend", this.getBoundingClientRect().top, index);
                    music.curSong.audio.currentTime = formatSongTimeText(music.curSong.lrc.timeArr[index]);
                    content.ontouchmove = null;
                }
            }
        }
    }, [music.curSong.url, music.isPlaying, music.toggleLyrics])

    function displayMusicLyr(lyricDom) {
        return function (lrcArr) {
            displayLyrics(lyricDom, lrcArr);
        }
    }
    let prevLine = null;

    function lyricUp(index) {
        let container = lyricWrapperRef.current,
            content = container.lastChild,
            initialTop = container.getBoundingClientRect().height / 2,
            lineHeight = container.lastChild.firstChild.offsetHeight,
            newTop = initialTop - lineHeight * index,
            curLine = content.children[index];
        content.style.top = `${newTop}px`;
        if (prevLine) prevLine.className = '';
        curLine.className = 'highlight';
        prevLine = curLine;
    }
    function clearLyrics() {
        console.log("clear lyrics");
        let container = lyricWrapperRef.current;
        if (container.lastChild && container.lastChild.className.indexOf('lyrics-content') >= 0) container.removeChild(container.lastChild);
    }

    return (
        <div className={`song-page-container page-container ${music && music.showSongPage ? 'slide-in' : ''}`}>
            <div className="header">
                <span className="iconfont icon--down-arrow" onClick={() => closeSongPage()}></span>
                {
                    music && music.curSong ? (
                        <div className="song-details">
                            <span>{music.curSong.name}</span>
                            <span>{generateArtists(music.curSong.artists)}</span>
                        </div>
                    ) : (<></>)
                }
                <span className="iconfont icon-loop" ></span>
            </div>
            <div className={`lyrics-container ${music.toggleLyrics ? 'show' : ''}`} onClick={() => toggleLyrics(false)}>
                <div className="volume-area">
                    <ProgressBar type={2} />
                </div>
                <div className="lyrics-area" ref={lyricWrapperRef}></div>
            </div>
            <div className={`disc-panel ${!music.toggleLyrics ? '' : 'fade-out'}`} onClick={() => toggleLyrics(true)}></div>
            <div className="audio-player-panel">
                <AudioController displayMusicLyr={displayMusicLyr(lyricWrapperRef.current)} lyricUp={lyricUp} clearLyrics={clearLyrics} />
            </div>
            <img className="song-bgimg" src={music.curSong.id ? music.curSong.album.blurPicUrl : ''}></img>
        </div>
    );
}

export default connect(mapStateToProps, mapDispatchToProps)(SongPage);